package com.bqtv.sport.ui.im

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import com.bqtv.sport.R
import com.bqtv.sport.app.AppActivity
import com.bqtv.sport.commen.dialog.MessageDialog
import com.bqtv.sport.databinding.ActivityFriendHomeBinding
import com.bqtv.sport.dialog.FriendHomeDialog
import com.bqtv.sport.dialog.SetFriendRemarkDialog
import com.google.gson.Gson
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.hjq.base.BaseDialog
import com.hjq.widget.view.SwitchButton
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMFriendInfo
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMSendCallback
import com.tencent.imsdk.v2.V2TIMUserStatus
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuicore.TUICore
import com.tencent.qcloud.tuikit.timcommon.bean.FriendProfileBean
import com.tencent.qcloud.tuikit.timcommon.component.impl.GlideEngine
import com.tencent.qcloud.tuikit.timcommon.util.ScreenUtil
import com.tencent.qcloud.tuikit.tuichat.TUIChatConstants
import com.tencent.qcloud.tuikit.tuichat.bean.CustomBusinessCardMessage
import com.tencent.qcloud.tuikit.tuichat.classicui.page.TUIC2CChatActivity
import com.tencent.qcloud.tuikit.tuichat.interfaces.FriendProfileListener
import com.tencent.qcloud.tuikit.tuichat.presenter.FriendProfilePresenter
import com.tencent.qcloud.tuikit.tuichat.util.ChatMessageBuilder
import com.tencent.qcloud.tuikit.tuiconversation.TUIConversationConstants

class FriendHomeActivity : AppActivity<ActivityFriendHomeBinding>() {
    private var isInBlackList = false
    private var friendProfileBean: FriendProfileBean? = null
    private lateinit var presenter: FriendProfilePresenter
    private var userId: String? = null

    companion object {
        public var INTENT_USER_ID = "user_id"
        fun start(context: Context, userId: String) {
            val intent = Intent(context, FriendHomeActivity::class.java)
            intent.putExtra(INTENT_USER_ID, userId)
            context.startActivity(intent)
        }
    }

    override fun getViewBinding() = ActivityFriendHomeBinding.inflate(layoutInflater)

    override fun initView() {
        userId = intent.getStringExtra(INTENT_USER_ID)
        presenter = FriendProfilePresenter()
        presenter.setProfileListener(object : FriendProfileListener {
            override fun onFriendProfileLoaded(friendProfileBean: FriendProfileBean) {
                setFriendProfile(friendProfileBean)
            }

            override fun onBlackListCheckResult(isInBlackList: Boolean) {
                this@FriendHomeActivity.isInBlackList = isInBlackList
            }

            override fun onFriendCheckResult(isFriend: Boolean) {
                if (isFriend) {
                    binding.llSetRemark.visibility = View.VISIBLE
                    binding.llRecommend.visibility = View.VISIBLE
                    binding.tvMsg.text = getString(R.string.send_message)
                    binding.tvMsg.setOnClickListener {
                        val intent = Intent(getContext(), TUIC2CChatActivity::class.java)
                        intent.putExtra(TUIConstants.TUIChat.CHAT_TYPE, V2TIMConversation.V2TIM_C2C)
                        intent.putExtra(
                            TUIConstants.TUIChat.CHAT_ID,
                            friendProfileBean?.getUserId()
                        )
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        getContext().startActivity(intent)
                    }

                    getTitleBar()?.setRightIconTint(R.color.text_222222)
                    getTitleBar()?.setOnTitleBarListener(object : OnTitleBarListener {
                        override fun onRightClick(titleBar: TitleBar?) {
                            super.onRightClick(titleBar)
                            var dialog = FriendHomeDialog.Builder(getContext())
                            dialog.setIsBlack(isInBlackList)
                            dialog.clickResult = object : FriendHomeDialog.Builder.ClickResult {
                                override fun onAddBlackClick() {
                                    if (isInBlackList) {
                                        deleteFromBlackList()
                                    } else {
                                        addToBlackList()
                                    }
                                }

                                override fun onDeleteFriendClick() {
                                    var msgDialog = MessageDialog.Builder(getContext())
                                        .setTitle(R.string.kind_reminder)
                                        .setMessage(R.string.sure_delete_friend)
                                        .setListener(object : MessageDialog.OnListener {
                                            override fun onConfirm(dialog: BaseDialog?) {
                                                removeFriend()
                                            }

                                        })
                                    msgDialog.show()
                                }

                            }
                            dialog.show()
                        }
                    })
                } else {
                    getTitleBar()?.setRightIconTint(R.color.white)
                    binding.llSetRemark.visibility = View.GONE
                    binding.llRecommend.visibility = View.GONE
                    binding.tvMsg.text = getString(R.string.add_friend)
                    binding.tvMsg.setOnClickListener(View.OnClickListener { v: View? ->
                        val bundle = Bundle()
                        bundle.putString(
                            TUIConstants.TUIContact.USER_ID,
                            friendProfileBean?.getUserId()
                        )
                        TUICore.startActivity(this, "AddMoreDetailActivity", bundle)
                    })
                }
            }

            override fun onConversationPinnedCheckResult(isPinned: Boolean) {
                binding.sbToTop.setChecked(isPinned)
            }

            override fun onMessageHasNotificationCheckResult(hasNotification: Boolean) {
                binding.sbMsgRev.setChecked(hasNotification)
            }
        })
    }

    override fun initData() {
        loadFriendProfile(userId)

        initListener()
    }

    fun loadFriendProfile(userID: String?) {
        presenter.loadFriendProfile(userID)
    }

    fun setFriendProfile(friendProfileBean: FriendProfileBean) {
        this.friendProfileBean = friendProfileBean

        val radius = ScreenUtil.dip2px(4.6f)
        GlideEngine.loadUserIcon(binding.friendIcon, friendProfileBean.getFaceUrl(), radius)

        binding.friendNickName.setText(friendProfileBean.getDisplayName())
        var ids = arrayListOf(friendProfileBean.getUserId())
        V2TIMManager.getInstance()
            .getUserStatus(ids, object : V2TIMValueCallback<List<V2TIMUserStatus>> {
                override fun onSuccess(t: List<V2TIMUserStatus>?) {
                    for (i in t!!) {
                        if (i.statusType == 1) {
                            binding.tvState.text = getString(R.string.online)
                        } else {
                            binding.tvState.text = getString(R.string.offline)
                        }
                    }
                }

                override fun onError(code: Int, desc: String?) {

                }
            })
    }

    private fun initListener() {

        binding.sbToTop.setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener {
            override fun onCheckedChanged(
                button: SwitchButton,
                isChecked: Boolean
            ) {
                pinConversation(isChecked)
            }

        })
        binding.sbMsgRev.setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener {
            override fun onCheckedChanged(
                button: SwitchButton,
                isChecked: Boolean
            ) {
                setNotificationMessage(
                    !isChecked
                )
            }

        })

        binding.llSetRemark.setOnClickListener {
            var remarkDialog = SetFriendRemarkDialog.Builder(getContext())
            remarkDialog.clickResult = object : SetFriendRemarkDialog.Builder.ClickResult {
                override fun onconfirmClick(text: String) {
                    var friendInfo = V2TIMFriendInfo();
                    friendInfo.setUserID(friendProfileBean?.userId);
                    friendInfo.setFriendRemark(text);
                    V2TIMManager.getFriendshipManager().setFriendInfo(friendInfo, object :
                        V2TIMCallback {
                        override fun onSuccess() {

                        }

                        override fun onError(code: Int, desc: String?) {

                        }

                    });
                }
            }
        }
        binding.llRecommend.setOnClickListener {
            recommendFriend()
        }
    }

    private fun removeFriend() {
        if (presenter == null || friendProfileBean == null) {
            return
        }
        presenter.removeFriend(friendProfileBean!!.getUserId())
    }

    private fun deleteFromBlackList() {
        if (presenter == null || friendProfileBean == null) {
            return
        }
        presenter.deleteFromBlackList(friendProfileBean!!.getUserId())
        isInBlackList = false
    }

    private fun addToBlackList() {
        if (presenter == null || friendProfileBean == null) {
            return
        }
        presenter.addToBlackList(friendProfileBean!!.getUserId())
        isInBlackList = true
    }

    private fun pinConversation(isPinned: Boolean) {
        if (presenter == null || friendProfileBean == null) {
            return
        }
        presenter.pinConversation(friendProfileBean!!.getUserId(), isPinned)
    }

    private fun setNotificationMessage(isNotification: Boolean) {
        if (presenter == null || friendProfileBean == null) {
            return
        }
        presenter.setMessageHasNotification(friendProfileBean!!.getUserId(), isNotification)
    }

    private fun recommendFriend() {
        val param = Bundle()
        param.putInt(
            TUIConversationConstants.GroupType.TYPE,
            TUIConversationConstants.GroupType.PUBLIC
        )
        param.putBoolean(TUIConversationConstants.FORWARD_CREATE_NEW_CHAT, false)
        TUICore.startActivityForResult(
            this,
            "ForwardSelectGroupActivity",
            param,
            object : ActivityResultCallback<ActivityResult?> {
                override fun onActivityResult(result: ActivityResult?) {
                    val data = result?.data
                    if (data != null) {
                        val chatMap =
                            data.getSerializableExtra(TUIChatConstants.FORWARD_SELECT_CONVERSATION_KEY) as HashMap<String, Boolean>?
                        if (chatMap == null || chatMap.isEmpty()) {
                            return
                        }
                        for ((id) in chatMap) {
                            val isSelfConversation = false
                            val gson = Gson()
                            val customMessage = CustomBusinessCardMessage()
                            customMessage.version = TUIChatConstants.version
                            customMessage.userID = friendProfileBean!!.getUserId()
                            customMessage.userName = friendProfileBean!!.getNickName()
                            customMessage.userHead = friendProfileBean!!.faceUrl
                            if (TextUtils.isEmpty(customMessage.userName)) {
                                customMessage.userName = friendProfileBean!!.userId
                            }
                            val data = gson.toJson(customMessage)
                            val info = ChatMessageBuilder.buildCustomMessage(
                                data,
                                customMessage.userName,
                                customMessage.userName.toByteArray()
                            )

                            V2TIMManager.getMessageManager()
                                .sendMessage(info.v2TIMMessage,
//                                                if (isGroup) null else id,
//                                                if (isGroup) id else null,
                                    id,
                                    null,
                                    V2TIMMessage.V2TIM_PRIORITY_DEFAULT,
                                    false,
                                    null,
                                    object : V2TIMSendCallback<V2TIMMessage?> {
                                        override fun onProgress(progress: Int) {

                                        }

                                        override fun onError(code: Int, desc: String) {

                                        }

                                        override fun onSuccess(v2TIMMessage: V2TIMMessage?) {
                                            // 这里直接返回，imsdk 状态还没更新，执行 login 会报错7009，所以需要 post 一下进行延时；

                                        }
                                    });
                        }
                    }
                }
            })
    }

    override fun onClick(view: View) {
        super.onClick(view)
        when (view) {

        }
    }
}